<template>
  <el-form label-width="100px">
    <!-- SPU名称 -->
    <el-form-item label="SPU名称">{{ spuInfo.spuName }} </el-form-item>

    <!-- SKU名称 -->
    <el-form-item label="SKU名称">
      <el-input placeholder="SKU名称" v-model="skuForm.skuName"></el-input>
    </el-form-item>

    <!-- 价格 -->
    <el-form-item label="价格(元)">
      <el-input placeholder="价格(元)" type="number" v-model="skuForm.price"></el-input>
    </el-form-item>

    <!-- 重量 -->
    <el-form-item label="重量(千克)">
      <el-input placeholder="重量(千克)" v-model="skuForm.weight"></el-input>
    </el-form-item>

    <!-- 规格描述 -->
    <el-form-item label="规格描述">
      <el-input placeholder="规格描述" type="textarea" rows="4" v-model="skuForm.skuDesc"></el-input>
    </el-form-item>

    <!-- 平台属性 -->
    <el-form-item label="平台属性">
      <el-form :inline="true">
        <el-form-item :label="attr.attrName" v-for="attr in spuAttrInfoList" :key="attr.id">
          <el-select placeholder="请选择" v-model="attr.attrIdValId">
            <el-option
              :value="`${attr.id}:${attrValue.id}`"
              :label="attrValue.valueName"
              v-for="attrValue in attr.attrValueList"
              :key="attrValue.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>

    <!-- 销售属性 -->
    <el-form-item label="销售属性">
      <el-form :inline="true">
        <el-form-item :label="saleAttr.saleAttrName" v-for="saleAttr in spuSaleAttrListInfo" :key="saleAttr.id">
          <el-select placeholder="请选择" v-model="saleAttr.attrIdValId">
            <el-option
              :value="`${saleAttr.id}:${saleAttrValue.id}`"
              :label="saleAttrValue.saleAttrValueName"
              v-for="saleAttrValue in saleAttr.spuSaleAttrValueList"
              :key="saleAttrValue.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>

    <!-- 图片列表 -->
    <el-form-item label="图片列表">
      <el-table border :data="spuImageInfoList" size="small" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="80" align="center"> </el-table-column>
        <el-table-column label="图片" prop="imgUrl">
          <template #default="{ row, $index }">
            <el-image :src="row.imgUrl" style="width: 60px; height: 60px"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="imgName"> </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row, $index }">
            <el-tag v-if="row.isDefault" type="success">默认</el-tag>
            <el-button v-else type="primary" size="small" @click="setDefaultImg(row)"> 设为默认 </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>

    <!-- 保存和取消按钮 -->
    <el-form-item>
      <el-button type="primary" @click="onSave">保存</el-button>
      <el-button @click="BackSpuList">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
// 导入暴露的枚举对象
import { STATUS } from '../../index.vue'
// 导入 vue
import { ref, onMounted } from 'vue'
// 导入 elmeent-plus
import { ElMessage } from 'element-plus'
// 导入api
import { spuSaleAttrList, spuImageList } from '@/api/spu'
import { attrInfoList } from '@/api/attr'
import { saveSkuInfo } from '@/api/sku'
// 导入类型
import type { saleAttrListModel, SpuInfoListModel, SpuSaleAttrData, SpuImageData } from '@/api/spu'
import type { attrDataModel } from '@/api/attr'
import type { SpuInfoModel } from '@/api/sku'
// 导入 useCategoryStore 仓库
import useCategoryStore from '@/stores/categoryStore'

// 接收父组件传递的方法
const emits = defineEmits<{
  (e: 'update:modelValue', statusValue: number): void
  (e: 'TransMitSpuInfo'): void
}>()
// 接收父组件传递的数据
const props = defineProps<{
  spuInfo: SpuInfoListModel
}>()

// 获取到仓库实例
const categoryStore = useCategoryStore()

// table表格假数据
// const tableData = [
//   {
//     date: '2016-05-03',
//     name: 'Tom',
//     address: 'No. 189, Grove St, Los Angeles'
//   }
// ]

// 点击取消按钮回调
const BackSpuList = () => {
  // 调用 并传递参数
  emits('update:modelValue', STATUS.SPULIST)
  emits('TransMitSpuInfo')
}
// 存储销售属性数据
const spuSaleAttrListInfo = ref<SpuSaleAttrData[]>([])

// 声明一个函数,用于再组件挂载完成时调用
// 此函数用于获取当前id的销售属性
const saleAttrlist = async () => {
  try {
    const res = await spuSaleAttrList(props.spuInfo.id!)
    // console.log(res)
    if (res.code === 200) {
      // 存储
      spuSaleAttrListInfo.value = res.data
      // console.log(spuSaleAttrListInfo.value)
    }
  } catch (error) {
    ElMessage.error('获取销售下拉数据失败.请重试')
  }
}

// 此变量用于存储三级分类的平台属性
const spuAttrInfoList = ref<attrDataModel[]>([])

// 此函数用于获取平台属性
const getAttrInfoList = async () => {
  try {
    // 从仓库中取出三级分类的id值
    let { category1Id, category2Id, category3Id } = categoryStore
    const res = await attrInfoList(category1Id as number, category2Id as number, category3Id as number)
    // 测试
    // console.log(res)
    // 判断业务状态码
    if (res.code === 200) {
      // 存储数据
      spuAttrInfoList.value = res.data
    }
  } catch (error) {
    ElMessage.error('获取三级分类数据失败,请重试')
  }
}

// 此常量用于存储图片列表数据
const spuImageInfoList = ref<SpuImageData[]>([])

// 此函数用于获取图片列表
const getImageInfoList = async () => {
  try {
    const res = await spuImageList(props.spuInfo.id!)
    // 测试
    // console.log(res)
    // 判断业务状态码
    if (res.code === 200) {
      // 存储
      spuImageInfoList.value = res.data
    }
  } catch (error) {
    ElMessage.error('获取图片列表失败,请重试')
  }
}

// 声明一个函数,用来初始化表单数据
const initSkuFrom = (): SpuInfoModel => ({
  spuId: undefined,
  price: '',
  skuName: '',
  skuDesc: '',
  weight: '',
  tmId: undefined,
  category3Id: undefined,
  skuDefaultImg: '',
  createTime: '',
  skuImageList: [],
  skuAttrValueList: [],
  skuSaleAttrValueList: []
})

// 声明一个变量,用来存储表单数据
const skuForm = ref<SpuInfoModel>(initSkuFrom())

const handleSelectionChange = (list: SpuImageData[]) => {
  console.log(list)
  // 存储图片列表数据
  skuForm.value.skuImageList = list!
}

// 点击设置默认值按钮回调函数,用于存储设置默认值的表单数据
const setDefaultImg = (row: SpuImageData) => {
  // 给每列数据都绑定一个isDefault属性
  // 循环绑定
  spuImageInfoList.value.forEach((item) => {
    // console.log(item)
    item.isDefault = false
  })
  // 让当前这一列数据的isDefault的状态设置成true
  row.isDefault = true
}

// 点击保存按钮回调
const onSave = async () => {
  // 组装数据
  // 组装spuId
  skuForm.value.spuId = props.spuInfo.id
  // 组装品牌id
  skuForm.value.tmId = props.spuInfo.tmId
  // 组装三级分类id
  skuForm.value.category3Id = categoryStore.category3Id
  // 组装默认图片
  skuForm.value.skuDefaultImg = spuImageInfoList.value.find((item) => item.isDefault)?.imgUrl!
  // 组装平台属性id和属性值id
  const selAttrList = spuAttrInfoList.value.filter((item) => item.attrIdValId)
  // console.log(selAttrList)

  skuForm.value.skuAttrValueList = selAttrList.map((item) => {
    console.log(item)

    const [attrId, valueId] = item.attrIdValId?.split(':')!
    return {
      attrId,
      valueId
    }
  })
  // 组装销售属性id和属性值id
  const selSaleAttrList = spuSaleAttrListInfo.value.filter((item) => item.attrIdValId)
  skuForm.value.skuSaleAttrValueList = selSaleAttrList.map((item) => {
    const [saleAttrId, saleAttrValueId] = item.attrIdValId?.split(':')!
    return {
      saleAttrId,
      saleAttrValueId
    }
  })

  // 发送请求
  try {
    const res = await saveSkuInfo(skuForm.value)
    console.log(res)
    if (res.code === 200) {
      // 提示
      ElMessage.success('保存成功')
      // 切换到主列表界面
      BackSpuList()
    }
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

// 在组件挂载完成之后发送请求
onMounted(() => {
  // 调用获取展示数据的回调函数
  saleAttrlist() // 根据当前列的id获取销售属性
  getAttrInfoList() // 获取三级分类平台数据
  getImageInfoList() // 根据当前列的id获取图片列表
})
</script>

<style scoped></style>
